//
//  AddCarViewController.m
//  FuelLog
//
//  Created by Pure Mass Communications on 9/8/08.
//  Copyright 2008 . All rights reserved.
//
//  Placed under GPL v2 with the kind permission of Pure Mass Communications
//
//  Modified to make compile under SDK 3.1 by Olaf Greck in May 2010
//
//
//  This program is free software; you can redistribute it and/or
//  modify it under the terms of the GNU General Public License
//  as published by the Free Software Foundation; either version 2
//  of the License, or (at your option) any later version.

//  This program is distributed in the hope that it will be useful,
//  but WITHOUT ANY WARRANTY; without even the implied warranty of
//  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
//  GNU General Public License for more details.

//  You should have received a copy of the GNU General Public License
//  along with this program; if not, write to the Free Software
//  Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.

#import "AddCarViewController.h"
#import "FuelLogAppDelegate.h"
#import "FuelLogViewController.h"
#import "CarsViewController.h"
#import "LoginViewController.h"
#import "DebugOutput.h"

@implementation AddCarViewController

@synthesize car;
@synthesize doneButton, carsButton, prefsButton ,statsButton ,addButton, toolBarSpacer;


- (void)reallyDelete {
	if (car.pk != -1) {
		FuelLogAppDelegate *appDelegate = (FuelLogAppDelegate *)[[UIApplication sharedApplication] delegate];
		if (car.selected ==1) {
			NSArray *allCars = appDelegate.cars;
			for(int i = 0; i < allCars.count; ++i) {
				Car *theCar = (Car *)[appDelegate.cars objectAtIndex:i];
				if (theCar.pk== 1) [theCar setSelected:YES];
			}
		}
		[appDelegate removeCar:car];
	}
	[self cancel:nil];
}

#pragma mark UIAlertView

- (void)alertDeleteCancelAction
{
	// open a alert with an OK and cancel button
	UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"" message:@"Delete this car and all of its fuel entries?"
		delegate:self cancelButtonTitle:@"Cancel" otherButtonTitles:@"Yes, Delete", nil];
	[alert show];
	[alert release];
}

#pragma mark UIAlertViewDelegate

- (void)alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)buttonIndex
{
	if (buttonIndex == [alert cancelButtonIndex]) {
		return;
	}
	[self reallyDelete];
}

#pragma mark UIViewController

// /*
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil {
	if (self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil]) {
    	doneButton = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemDone
					  //style:UIBarButtonItemStylePlain
																   target:self
																   action:@selector(done:)];
		self.navigationItem.rightBarButtonItem = doneButton;
		carsButton = [[UIBarButtonItem alloc] initWithTitle: (NSLocalizedString(@"Cars", @""))
													  style:UIBarButtonItemStyleBordered
													 target:self
													 action:nil];
		prefsButton = [[UIBarButtonItem alloc] initWithTitle: (NSLocalizedString(@"Prefs", @""))
													   style:UIBarButtonItemStyleBordered
													  target:self
													  action:nil];
		statsButton = [[UIBarButtonItem alloc] initWithTitle: (NSLocalizedString(@"Stats", @""))
													   style:UIBarButtonItemStyleBordered
													  target:self
													  action:nil];
		addButton = [[UIBarButtonItem alloc ] initWithTitle: (NSLocalizedString(@"Add", @""))
													  style:UIBarButtonItemStyleBordered
													 target:self
													 action:@selector(addCar:)];
		carsButton.enabled = NO;
		prefsButton.enabled = NO;
		statsButton.enabled = NO;
		addButton.enabled = YES;
		toolBarSpacer = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace
																	  target:self
																	  action:nil];
		[self setToolbarItems:[NSArray arrayWithObjects:carsButton, 
							   toolBarSpacer, prefsButton,
							   toolBarSpacer, statsButton,
							   toolBarSpacer, addButton,
							   nil] animated:NO];
	}
	debug(@"in initWithNibName");
	return self;
}
// */
 
// /*
// Implement loadView if you want to create a view hierarchy programmatically
- (void)loadView {
}
-(void)setupButtons {
	int maxWidth = 320;
 self.view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, maxWidth, 460)];
	float startX = self.view.bounds.origin.x;
	float startY = self.view.bounds.origin.y; 
	
	float carBoxWidth = 170;
	float carBoxHight = 40;
	float carBoxOriginX = startX+ (maxWidth - carBoxWidth)/2;
	float carBoxOriginY = startY+  20;
	float distance = 20;
	
	float ButtonWidth = 110;
	float ButtonHight = 40;
	float exportButtonOriginX = startX+ (maxWidth - ButtonWidth)/2;
	float exportButtonOriginY = carBoxOriginY + carBoxHight + distance;

//	int deleteButtonWidth = 110;
//	int deleteButtonHight = 40;
	float deleteButtonOriginX = startX+ (maxWidth - ButtonWidth)/2;
	float deleteButtonOriginY = exportButtonOriginY + ButtonHight + distance;
	
	self.view.backgroundColor = [UIColor groupTableViewBackgroundColor];
	carBox = [[UITextField alloc] initWithFrame:CGRectMake(carBoxOriginX, carBoxOriginY, carBoxWidth, carBoxHight)];
	[carBox setBorderStyle:UITextBorderStyleRoundedRect];
	[carBox setContentHorizontalAlignment:UIControlContentHorizontalAlignmentCenter];
	[carBox setContentVerticalAlignment:UIControlContentVerticalAlignmentCenter];
#pragma mark FIXME rounded corners and square view dont match 100%
	/*/	carBox.text = @"only Xcode";
	carBox.textAlignment = UITextAlignmentCenter;
	carBox.textColor = [UIColor yellowColor];
//	carBox.shadowColor = [UIColor whiteColor];
//	carBox.shadowOffset = CGSizeMake(1,1);
	carBox.font = [UIFont fontWithName:@"Zapfino" size:20];
*/	carBox.backgroundColor = [UIColor groupTableViewBackgroundColor];
	[self.view addSubview:carBox];

	exportButton = [UIButton buttonWithType:UIButtonTypeRoundedRect];
	[exportButton setFrame:CGRectMake(exportButtonOriginX, 
											 exportButtonOriginY, 
											 ButtonWidth, ButtonHight)];
	[exportButton setTitle:@"Export" forState:UIControlStateNormal];
//	[exportButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
//	[exportButton setBackgroundColor:[UIColor blueColor]];
/*	[exportButton setTitle:@"Export" forState:UIControlStateNormal];

	[exportButton setTitle: @"myTitle" forState: UIControlStateApplication];
	[exportButton setTitle: @"myTitle" forState: UIControlStateHighlighted];
	[exportButton setTitle: @"myTitle" forState: UIControlStateReserved];
	[exportButton setTitle: @"myTitle" forState: UIControlStateSelected];
	[exportButton setTitle: @"myTitle" forState: UIControlStateDisabled];
*/	
	[exportButton setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
	exportButton.contentHorizontalAlignment = UIControlContentHorizontalAlignmentCenter;
	exportButton.backgroundColor = [UIColor groupTableViewBackgroundColor];
	[exportButton addTarget:self action:@selector(exportCar:) forControlEvents:UIControlEventTouchUpInside];
	[self.view addSubview:exportButton];
	if (car.pk != 1)  
	{
	deleteButton = [UIButton buttonWithType:UIButtonTypeRoundedRect]; 
	[deleteButton setFrame:CGRectMake(deleteButtonOriginX, 
											 deleteButtonOriginY, 
											 ButtonWidth, ButtonHight)];
	[deleteButton setTitle:@"Delete" forState:UIControlStateNormal];;
//	[deleteButton setTitle:@"Alert :D " forState:UIControlEventTouchDown];
	[deleteButton setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
	deleteButton.contentHorizontalAlignment = UIControlContentHorizontalAlignmentCenter;
	[deleteButton setBackgroundColor:[UIColor groupTableViewBackgroundColor]];
//no visible effect:	[deleteButton setOpaque:NO];
	[deleteButton addTarget:self action:@selector(deleteCar:) forControlEvents:UIControlEventTouchUpInside];
	[self.view addSubview:deleteButton];
}
}
// */ 

- (void)viewDidLoad {
	[self setupButtons];
	carBox.text = car.label;
	carBox.clearButtonMode = UITextFieldViewModeWhileEditing;
	[errorText setText:@""];
}

- (void)viewWillAppear:(BOOL)animated {
	[super viewWillAppear:animated];
	[self setLabel];
}


- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
	// Return YES for supported orientations
	return (interfaceOrientation == UIInterfaceOrientationPortrait);
}


- (void)didReceiveMemoryWarning {
	[super didReceiveMemoryWarning]; // Releases the view if it doesn't have a superview
	// Release anything that's not essential, such as cached data
}


- (void)dealloc {
	[carBox release];
	[errorText release];
	[deleteButton release];
	[doneButton release];
	[carsButton release];
	[prefsButton release];
	[statsButton release];
	[addButton release];
	[toolBarSpacer release];
	[super dealloc];
}

- (IBAction)cancel:(id)sender {
	[errorText setText:@""];
	[car release];
	[carBox resignFirstResponder];
//obsolete:	[self dismissModalViewControllerAnimated:YES];
//	CarsViewController *cvc = (CarsViewController *)self.parentViewController;
//	[cvc clickSelectedCar];
	[self.navigationController popViewControllerAnimated:YES];
#pragma mark FIXME clickSelectedCar 1
}

- (IBAction)done:(id)sender {
	NSString *name = [carBox.text stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
	[carBox setText:name];
	if ([name length] == 0) {
		[errorText setText:@"Please enter a label."];
		return;
	}
	BOOL changed = ![name isEqualToString:car.label];
    FuelLogAppDelegate *appDelegate = (FuelLogAppDelegate *)[[UIApplication sharedApplication] delegate];
	if ((car.pk <= 0 || changed) && [appDelegate hasCar:name]) {
		[errorText setText:@"Another car has the same label.  Please enter a different label."];
		return;
#pragma mark FIXME return in non-void??
	}
	[car setLabel:name];
	[errorText setText:@""];
	if (car.pk == -1) {
		[appDelegate addCar:car];
	}
	[car release];
	[carBox resignFirstResponder];
//obsolete:	[self dismissModalViewControllerAnimated:YES];
	[self.navigationController popViewControllerAnimated:YES];
	CarsViewController *cvc = (CarsViewController *)self.parentViewController;
#pragma mark FIXME clickSelectedCar 2
	[cvc clickSelectedCar];
}

- (IBAction)deleteCar:(id)sender {
	[self alertDeleteCancelAction];
}

- (IBAction)exportCar:(id)sender {
	debug(@"in exportCar");
	LoginViewController *loginController = [FuelLogViewController loginViewController];
	[loginController setMode:FUELLOG_EXPORT];
	[loginController setCar:car];
	[self presentModalViewController:loginController animated:YES];
}

- (BOOL)textFieldShouldReturn:(UITextField *)theTextField {
	NSString *name = [carBox.text stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
	[carBox setText:name];
	if ([name length] == 0) {
		[errorText setText:@"Please enter a label."];
		return NO;
	}
	BOOL changed = ![name isEqualToString:car.label];
    FuelLogAppDelegate *appDelegate = (FuelLogAppDelegate *)[[UIApplication sharedApplication] delegate];
	if ((car.pk <= 0 || changed) && [appDelegate hasCar:name]) {
		[errorText setText:@"Another car has the same label.\nPlease enter a different label."];
		return NO;
	}
	[errorText setText:@""];
	[carBox resignFirstResponder];
	return YES;
}

- (void)setLabel {
	debug(@"in setLabel");
	if (car.pk == -1) {
		deleteButton.hidden = YES;
		exportButton.hidden = YES;
	} else {
		deleteButton.hidden = NO;
		exportButton.hidden = NO;
	}
	[carBox setText:car.label];
	[errorText setText:@""];
}

@end
